#!/usr/bin/env node

const http = require('http'),
      fs = require('fs');
const movieList = require('./data');
const index =  fs.readFileSync('index.html');

http.createServer((req, res) => {
    let dataList = [];
    for(let i = 0; i < movieList.length; i++) {
        let score = movieList[i]['movieRange']
        if(score !== "暂无评分") {
            let id = movieList[i]['movieId'];
            let name = movieList[i]['movieName'];
            const movieData = {
                movieId: id,
                movieName: name,
                movieRange: score
            };
            dataList.push(movieData);
        }
    }
    for(let i=0; i < dataList.length-1; i++) {
        for(let j=0; j<dataList.length-i-1; j++) {
            if(Number(dataList[j]['movieRange']) < Number(dataList[j+1]['movieRange'])) {
                let temp = dataList[j+1];
                dataList[j+1] = dataList[j];
                dataList[j] = temp;                                                                
            }
        }
    }
    if (req.url === '/') {
        res.setHeader('Content-Type', 'text/html');
        res.end(index);
    } else if (req.url === '/getlist') {
        res.setHeader('Content-Type', 'text/plain;charset=utf-8');
        res.end(JSON.stringify(dataList));
    }

}).listen(8080);
